<?php
/**
 *  ### Using the alias `i0' for the tree index table
 *
 *
 */
namespace Dclub\modules\Catalog;

class Action_SelectTreeBranchByType
    extends Action_SelectTreeAbstract
{

    /**
     *  @var int ?
     */
    protected $typeId;

    /**
     *  @var string
     */
    protected $typeName;


    /************************************
     *         Public methods          *
     ************************************/


    /** assign name of the type (the branch's root node)
     *  mutually exclusive with setTypeId() : will remove any set typeId
     *  @param string $typeName
     *  @return this
     */
    public function setTypeName( $typeName )
    {
        debug();
        $this->typeName = \Yz_String::testNotEmpty($typeName);
        $this->typeId = null;
        return $this;
    }


    /** assign id of the type (the branch's root node)
     *  mutually exclusive with setTypeName() : will remove any set typeName
     *  @param int $typeId
     *  @return this
     */
    public function setTypeId( $typeId )
    {
        debug();
        $this->typeId = \Yz_Int::testPositive($typeId);
        $this->typeName = null;
        return $this;
    }



    /************************************
     *       Protected methods          *
     ************************************/


    /**
     *  Modified SELECT statement creator
     *
     */
    protected function buildSelect()
    {
        debug();

        if (null !== $this->typeId) {
            $builder = 'buildSelectForTypeId';
        } else if (null !== $this->typeName) {
            $builder = 'buildSelectForTypeName';
        } else {
            throw new \Yz_Exception("Neither name nor id set for the root type");
        }
        $sql = parent::buildSelect();
        return $this->$builder($sql);
    }

    /**
     *
     */
    protected function buildSelectForTypeId($sql)
    {
        debug();
        $ti = self::TABLE_INDEX;

        // assume join with TABLE_INDEX already done
        return $sql
            ->where("{$ti}.parentId=:_typeId")
            ->bind('_typeId', $this->typeId)
            ->orderBy("{$ti}.id")
        ;
    }

    /**
     *
     */
    protected function buildSelectForTypeName($sql)
    {
        debug();
        $ti = self::TABLE_INDEX;
        $tn = self::TABLE_TREE . 'n';

        // assume join with TABLE_INDEX already done
        return $sql
            ->joinTable(
                \Yz_SQL_Join::leftJoin($this->tableTree, $tn)
                    ->joinOn("{$ti}.parentId={$tn}.id")
                )
            ->where("{$tn}.name=:_typeName AND {$tn}.parentId=0")
            ->bind('_typeName', $this->typeName)
            ->orderBy("{$ti}.id")
        ;
    }



}
